<template>
  <div class="user-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-autocomplete
          class="inline-input"
          v-model="userInput"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          :trigger-on-focus="false"
          clearable
          @clear="onClearProc"
          @select="handleSelect"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="onSearch"
          ></el-button
        ></el-autocomplete>
      </el-col>
      <el-col :span="12">
        <add-dialog @transferUser="addUsered"></add-dialog>
      </el-col>
    </el-row>
    <!--#region 表格数据 -->
    <el-table
      id="data"
      :data="userList"
      border
      stripe
      :row-style="{ height: '0' }"
      :cell-style="{ padding: '6px 0' }"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
    >
      <el-table-column type="index"></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        sortable
        align="center"
      >
        <template slot-scope="scope">
          <div class="center">
            <i class="el-icon-date pr1"></i>
            {{ new Date(scope.row.createTime).toLocaleDateString() }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="用户" sortable align="center">
      </el-table-column>

      <el-table-column prop="role" label="角色" align="center">
        <template slot-scope="scope">
          <div class="center">
            {{ scope.row.role.name }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-row class="center">
            <el-col :span="8" class="center">
              <ps-putuser :user="scope.row"></ps-putuser
            ></el-col>
            <el-col :span="8" class="center"
              ><el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="deleteUser(scope.row)"
              ></el-button
            ></el-col>
            <el-col :span="8" class="center">
              <el-tooltip
                class="item"
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <xy-assignroles
                  :user="scope.row"
                  @selectedRoles="selectedRoles"
                ></xy-assignroles> </el-tooltip
            ></el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- #endregion -->

    <!-- #region 分页-->
    <el-row class="user-footer" type="flex" justify="space-between">
      <el-col :span="23">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageIndex"
          :page-sizes="[1, 2, 5, 10, 15, 100]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
      <el-col :span="1">
        <el-button class="exportFile" size="mini" @click="exportFile"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <!-- #endregion -->
  </div>
</template>

<script>
import DialogAdd from "./AddUser.vue";
import PutUser from "./PutUser";
import AssignRoles from "./AssignRoles.vue";
// import userData from "./userData";
export default {
  components: {
    "add-dialog": DialogAdd,
    "ps-putuser": PutUser,
    "xy-assignroles": AssignRoles,
  },
  data() {
    return {
      userList: [],
      queryInfo: {
        query: "",
        // 当前页数
        pageIndex: 1,
        // 当前页数据大小
        pageSize: 5,
      },
      total: 0,
      restaurants: [],
      userInput: "",
    };
  },
  created() {
    this.getUserList();
  },
  mounted() {
    this.restaurants = this.userList;
  },
  methods: {
    async onSearch() {
      this.getUserList();
    },
    /**
     * 获取用户列表
     * @param {Type} none
     * @returns  void
     */
    async getUserList() {
      // console.log(userData);
      let response = await this.$http.Get("/api/Users", this.queryInfo);

      console.log(response);
      if (response.ok) {
        this.userList = response.data.list;
        this.total = response.data.total;
      }
    },
    /**
     * 每页数据大小变化时调用
     * @param newPageSize 新的页面大小
     * @returns  none
     */
    handleSizeChange(newPageSize) {
      console.log(newPageSize);
      this.queryInfo.pageSize = newPageSize;
      this.getUserList();
    },
    // 页码变化
    handleCurrentChange(newPageIndx) {
      console.log(newPageIndx);
      this.queryInfo.pageIndex = newPageIndx;
      this.getUserList();
    },
    // 用户可用状态
    async userStateChange(userInfo) {
      // console.log(userInfo);
      let a = await this.$myhttp.patch("User", userInfo.userName, userInfo);
      console.log({ a });
    },
    /**
     * 点击清理的回调函数
     * @param none
     * @returns  none
     */
    onClearProc() {
      this.getUserList();
    },
    test(url, ...args) {
      console.log(url);
      console.log(args);
    },
    addUsered(user) {
      this.userList = [user];
      this.total = 1;
    },
    async deleteUser(user) {
      console.log(user);
      this.$confirm(`确认删除 ${user.userName}？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.userList = this.userList.filter(
            (v) => v.userName != user.userName
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      // await this.$myhttp.Delete("UserRoles", user.userName, user);
      // this.getUserList();
    },

    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      results.forEach((v) => {
        v.value = v.userName;
      });
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.userName
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      };
    },
    handleSelect(item) {
      this.userList = [item];
    },

    exportFile() {
      const jsonData = this.userList;
      let title = {
        userName: "用户名",
        email: "邮箱",
        phone: "电话",
        roleName: "角色",
        createTime: "创建时间",
        state: "状态",
        imageSrc: "图标Url",
      };
      const titleKey = Object.keys(title);
      // 列标题，逗号隔开，每一个逗号就是隔开一个单元格
      let str = "";
      // let str = `创建时间,用户名,邮箱,电话,角色,状态,图标\n`;
      for (let i = 0; i < titleKey.length; i++) {
        str += title[titleKey[i]];
        if (i + 1 !== titleKey.length) {
          str += ",";
        } else {
          str += "\n";
        }
      }
      // 增加\t为了不让表格显示科学计数法或者其他格式
      for (let i = 0; i < jsonData.length; i++) {
        for (const key in title) {
          str += `${jsonData[i][key] + "\t"},`;
        }
        str += "\n";
      }
      // encodeURIComponent解决中文乱码
      const uri =
        "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      // 通过创建a标签实现
      const link = document.createElement("a");
      link.href = uri;
      // 对下载的文件命名
      link.download = "json数据表.csv";
      link.click();
    },
    selectedRoles(data) {
      console.log(data);
    },
  },
};
</script>

<style lang="less" scoped>
.user-container {
  background-color: #fff;
  height: 100%;
  .el-autocomplete {
    width: 100%;
  }
  .el-table {
    margin-top: 15px;

    .el-tooltip {
      margin-left: 0;
    }
  }
  .el-pagination {
    margin-top: 15px;
  }
  .user-footer {
    display: flex;
    align-items: center;
    .exportFile {
      margin-top: 15px;
    }
  }
}
</style>
